package cc.smarnet.caihou.phone.bracts;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.smarnet.caihou.IPConfig;

import cc.smarnet.caihou.LoginActivity;
import cc.smarnet.caihou.R;
import cc.smarnet.caihou.util.DateUtil;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 新增毛产品的activity
 */
public class BractsAddActivity extends AppCompatActivity {
    private ImageButton imageButton;
    private Spinner baseNameSpinner;//所属基地
    private Spinner greenhouseNameSpinner;//所属大棚
    private EditText varietyDictTextEditText;//采收品种;
    private EditText harvestWeightEditText;//采收重量
    private EditText harvestCountEditText;//采收支数
    private EditText harvestTimeEditText;//采摘日期
    private EditText harvestUserEditText;//采摘人
    private Button confirmButton;
    private ProgressBar progressBar;


    private String token;

    List<String> baseNameList = new ArrayList<>();
    List<String> greenhouseNameList = new ArrayList<>();
    String[] varietyDictTextArray;

    List<String> baseNameIdList = new ArrayList<>();
    List<String> greenhouseNameIdList = new ArrayList<>();


    private String baseNameId;//所属基地id
    private String greenhouseNameId;//所属大棚id
    private String varietyDictText;//采收品种
    private float harvestWeight;//采收重量
    private int harvestCount;//采收支数
    private String harvestTime;//采摘日期
    private String harvestUser;//采摘人

    int mYear, mMonth, mDay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bracts_add);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        varietyDictTextEditText.clearFocus();//使采收品种框失去焦点
        progressBar.setVisibility(View.GONE);

        harvestTime= DateUtil.currentDate();
        harvestTimeEditText.setText(harvestTime);//设置默认的采摘日期

        getToken();
        /*
         * 获取基地的数据并设置在spinner中，然后再获取大棚的数据并设置在spinner。
         * 只有先有了基地的数据才能获取到相应大棚的数据
         * */
        getBaseName();
        getVarietyDictText();//获取采收品种

        getDate();// 获取当前的日期
        // 选择采摘日期的监听
        harvestTimeEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(BractsAddActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int day) {
                                mYear = year;
                                mMonth = month;
                                mDay = day;
                                String transMonth = String.format("%02d", mMonth + 1);// 如果月份小于10的话进行补0
                                String transDay = String.format("%02d", mDay);// 如果日小于10的话进行补0
                                harvestTime = mYear + "-" + transMonth + "-" + transDay;
                                harvestTimeEditText.setText(harvestTime);
                            }
                        }, mYear, mMonth, mDay);
                datePickerDialog.show();
            }
        });
        // 点击确认按钮的监听
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取采收重量的值
                if (!harvestWeightEditText.getText().toString().equals("")) {
                    harvestWeight = Float.valueOf(harvestWeightEditText.getText().toString());
                }
                // 获取采摘人
                harvestUser = harvestUserEditText.getText().toString();
                // 获取采收支数的值
                if (harvestCountEditText.getText().toString().equals("")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(BractsAddActivity.this).create();
                    alertDialog.setMessage("请输入采收支数！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                } else {
                    harvestCount = Integer.parseInt(harvestCountEditText.getText().toString());
                }

                if (harvestTimeEditText.getText().toString().equals("点击选择日期")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(BractsAddActivity.this).create();
                    alertDialog.setMessage("请选择采摘日期！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                }
                // 新增毛产品信息
                addBracts();
            }
        });
        // 点击采收品种输入框的监听
        varietyDictTextEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean[] checkedItems = new boolean[varietyDictTextArray.length];
                for (int i = 0; i < checkedItems.length; i++) {
                    checkedItems[i] = false;
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(BractsAddActivity.this);
                builder.setMultiChoiceItems(varietyDictTextArray, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < checkedItems.length; i++) {
                            //判断一下是选中的
                            if (checkedItems[i]) {
                                //把选中的采收品种取出来     数据在哪里存着就去哪里取
                                String variety = varietyDictTextArray[i];
                                sb.append(variety + ",");
                            }
                        }
                        varietyDictText = sb.toString();
                        if (varietyDictText.length() > 0) {
                            varietyDictText = varietyDictText.substring(0, varietyDictText.length() - 1);// 去掉最后的一个逗号
                        }
                        varietyDictTextEditText.setText(varietyDictText);
                        dialog.dismiss();
                    }
                });
                builder.show();
            }
        });

        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void initViews() {
        imageButton = findViewById(R.id.bracts_add_return);
        baseNameSpinner = findViewById(R.id.bracts_add_baseName_spinner);
        greenhouseNameSpinner = findViewById(R.id.bracts_add_greenhouseName_spinner);
        harvestWeightEditText = findViewById(R.id.bracts_add_harvestWeight_editText);
        harvestCountEditText = findViewById(R.id.bracts_add_harvestCount_editText);
        harvestTimeEditText = findViewById(R.id.bracts_add_harvestTime_editText);
        harvestUserEditText = findViewById(R.id.bracts_add_harvestUser_editText);
        confirmButton = findViewById(R.id.bracts_confirm_add_button);
        progressBar = findViewById(R.id.bracts_add_progressBar);
        varietyDictTextEditText = findViewById(R.id.bracts_add_varietyDictText_editText);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }

    // 获取基地
    public void getBaseName() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + "/flower/plantingBase/getAllBase";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .connTimeOut(10 * 60 * 1000)
                .readTimeOut(10 * 60 * 1000)
                .writeTimeOut(10 * 60 * 1000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(BractsAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(BractsAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                baseNameList.add(name);
                                baseNameIdList.add(jsonObj.getString("id"));
                            }

                            if (baseNameList.size() > 0) {// 如果baseNameList有值的话为baseNameSpinner赋值，然后获取第一个基地下大棚的数据
                                baseNameId = baseNameIdList.get(0);//设置默认的基地的id
                                baseNameSpinner();
                                getGreenhouseName(baseNameIdList.get(0));
                            }
                        }
                    }
                });
    }

    // 获取大棚
    public void getGreenhouseName(String baseNameId) {
        String url = IPConfig.baseUrl + "/flower/flowerPlantingGreenhouse/queryByParentId/" + baseNameId;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .connTimeOut(10 * 60 * 1000)
                .readTimeOut(10 * 60 * 1000)
                .writeTimeOut(10 * 60 * 1000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        /*Toast.makeText(BractsAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(BractsAddActivity.this, LoginActivity.class);
                        startActivity(intent);*/
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        greenhouseNameList.clear();
                        confirmButton.setClickable(true);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                greenhouseNameList.add(name);
                                greenhouseNameIdList.add(jsonObj.getString("id"));
                            }
                            if (greenhouseNameList.size() > 0) {
                                greenhouseNameId = greenhouseNameIdList.get(0);//设置默认大棚的id
                                greenhouseNameSpinner();
                            }
                        } else {
                            // 如果没有取到大棚的数据，那么弹窗提示，在弹窗中点击了确定按钮后，并且使确定按钮不可用
                            AlertDialog alertDialog = new AlertDialog.Builder(BractsAddActivity.this).create();
                            alertDialog.setMessage("所选基地无大棚信息，无法进行新增毛产品信息操作！");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    greenhouseNameSpinner();
                                    confirmButton.setClickable(false);
                                }
                            });
                            alertDialog.show();
                        }
                    }
                });
    }

    // 获取采收品种
    public void getVarietyDictText() {
        String url = IPConfig.baseUrl + "/flower/flowerVariety/list";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .connTimeOut(10 * 60 * 1000)
                .readTimeOut(10 * 60 * 1000)
                .writeTimeOut(10 * 60 * 1000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(BractsAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(BractsAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            varietyDictTextArray = new String[jsonArray.size()];
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                varietyDictTextArray[i] = name;
                            }
                        }
                    }
                });
    }

    //所属基地的spinner
    public void baseNameSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, baseNameList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        baseNameSpinner.setAdapter(adapter);
        baseNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                baseNameId = baseNameIdList.get(i);
                getGreenhouseName(baseNameId);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //所属大棚的spinner
    public void greenhouseNameSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, greenhouseNameList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        greenhouseNameSpinner.setAdapter(adapter);
        greenhouseNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                greenhouseNameId = greenhouseNameIdList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    // 新增毛产品信息
    public void addBracts() {
        confirmButton.setClickable(false);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sourceBase", baseNameId);//基地id
        map.put("sourceGreenhouse", greenhouseNameId);//大棚id
        map.put("variety", varietyDictText);//采收品种
        map.put("harvestWeight", harvestWeight);//采收重量
        map.put("harvestCount", harvestCount);//采收支数
        map.put("harvestTime", harvestTime);//采摘日期
        map.put("harvestUser", harvestUser);//采摘人
        String requestJsonString = JSON.toJSONString(map);
        String url = IPConfig.baseUrl + "/flower/harvest/add";
        OkHttpUtils
                .postString()
                .addHeader("X-Access-Token", token)
                .url(url)
                .content(requestJsonString)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .connTimeOut(10 * 60 * 1000)
                .readTimeOut(10 * 60 * 1000)
                .writeTimeOut(10 * 60 * 1000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        confirmButton.setClickable(true);
                        Toast.makeText(BractsAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(BractsAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        confirmButton.setClickable(true);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            AlertDialog alertDialog = new AlertDialog.Builder(BractsAddActivity.this).create();
                            alertDialog.setMessage("毛产品信息新增成功");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(BractsAddActivity.this, BractsActivity.class);
                                    startActivity(intent);
                                }
                            });
                            alertDialog.setCanceledOnTouchOutside(false);
                            alertDialog.show();
                        }
                    }
                });
    }

    // 获取当前日期
    public void getDate() {
        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
    }
}